package cn.bitkit.component.redis;

import cn.bitkit.base.exception.BusinessAssert;
import cn.bitkit.component.context.SpringContext;
import cn.bitkit.base.util.RandomUtil;
import cn.bitkit.base.util.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

/**
 * 通用实体编码
 * @author changbo
 */
public class EntityCodeHelper {

    /**
     * redis方式增长
     */
    public static String getCode(String type){
        StringRedisTemplate stringRedisTemplate = SpringContext.getAssertedBean(StringRedisTemplate.class);
        BusinessAssert.isNotNull(stringRedisTemplate, "编号生成失败");
        long day = System.currentTimeMillis()/(24*60*60*1000);
        String dayStr = StringUtil.leftPad(Long.toString(day), '0', 5);
        String key = BasicRedisKey.BASIC_ENTITY_CODE + type + dayStr;
        int increment = RandomUtil.random(1, 9);
        stringRedisTemplate.opsForValue().setIfAbsent(key, "100", Duration.ofDays(1));
        Long seq = stringRedisTemplate.opsForValue().increment(key, increment);
        BusinessAssert.isNotNull(seq, "编号生成失败");
        String seqStr = StringUtil.leftPad(Long.toString(seq), '0', 5);
        //14位=4+5+5
        return type + dayStr + seqStr;
    }

}
